package wh.排序算法.快速排序;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/5 10:45
 * @description:
 * @version:
 */
public class QuickSort {
    public static void quickSort(int[] arr,int low,int high) {
        int i,j,temp,t;
        //这里必不可少，不然陷入死循环
        if(low>high){
            return;
        }
        i=low;
        j=high;
        //temp就是基准位
        temp = arr[low];

        while (i<j) {
            //先看右边，依次往左递减
            while (temp<=arr[j]&&i<j) {
                j--;
            }
            //再看左边，依次往右递增
            while (temp>=arr[i]&&i<j) {
                i++;
            }
            //如果满足条件则交换
            if (i<j) {
                t = arr[j];
                arr[j] = arr[i];
                arr[i] = t;
            }
        }
        //最后将基准为与i和j相等位置的数字交换
        arr[low] = arr[i];
        arr[i] = temp;
        //递归调用左半数组
        quickSort(arr, low, j-1);
        //递归调用右半数组
        quickSort(arr, j+1, high);
    }

    public static void test2(int[] arr ,int low,int high) {
        if (low > high) {
            return;
        }
        int i,j,tmp,target;
        i = low;
        j = high;
        target = arr[low];
        while (i < j) {
            while (i < j && arr[j] >= target) {
                j--;
            }
            while (i < j && arr[i] <= target) {
                i++;
            }
            if (i < j) {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
        }
        arr[low] = arr[i];
        arr[i] = target;
        test2(arr,low,i-1);
        test2(arr,i+1,high);
    }

    public static void test(int[] arr,int low ,int high) {
        if (low > high) {
            return;
        }
        int i,j,target,tmp;
        i = low;
        j = high;
        target = arr[low];
        while (i < j) {
            while (i < j && arr[j] >= target) {
                j--;
            }
            while (i < j && arr[i] <= target) {
                i++;
            }
            if (i < j) {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
        }
        arr[low] = arr[i];
        arr[i] = target;
        test(arr,low,i - 1);
        test(arr,i+1,high);
    }



    public static void main(String[] args){
        int[] arr = {10,7,2,4,7,62,3,4,2,1,8,9,19};
        test(arr, 0, arr.length-1);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}